<?php

/**
 * User: luchao
 * Createtime: 2016/10/20 16:03
 * desc：变更单
 */
namespace AuctionCore\ChangeOrder;

use AuctionCore\Account\Back\Employee;
use AuctionCore\CarResource\CarModel;
use AuctionCore\AuctionOrder\AuOrder;
use AuctionCore\Cashier\Payment;
use AuctionCore\Cashier\Collection;
use AuctionCore\CarDealer\AssetCenter;
use AuctionCore\CarResource\BreachCar;
use AuctionCore\CarResource\SelfReceiveCar;
use AuctionCore\PurchaseOrder\PurchaseOrder;
use AuctionCore\Dispute\Dispute;
use AuctionCore\CarResource\Car;
use AuctionCore\CarResource\CarSource;
use AuctionCore\AuctionOrder\Transfer;
use AuctionCore\CarDealer\Dealer;
use Think\Log;
use AuctionBack\Logic\CarReportLogic;

class ChangeOrder
{
    const STATUS_WAIT = 0; // 待执行
    const STATUS_ALREADY = 1; // 已执行
    const STATUS_COMPLETE = 2; // 完成
    const STATUS_REFUSE = 3; // 拒绝执行
    const STATUS_CANCEL = 4; // 作废
    protected $mid = null;

    public function __construct($mid)
    {
        $this->mid = $mid;
    }


    public static function create($data)
    {
        return M('modify_list')->add($data);
    }

    /**
     * 变更单创建
     * @return  bool
     */
    public static function CreateChangeOrder($data)
    {
        //事务开始
        M()->startTrans();
        $time = date('Y-m-d H:i:s');
        $modify_no = genBillsNo('BG', '1');
        $add_ChangeOrder_data = [
            'modify_no' => $modify_no,
            'order_id' => $data['order_id'],
            'order_no' => $data['order_no'],
            'po_id' => $data['po_id'],
            'po_no' => $data['po_no'],
            'sid' =>$data['sid'],
            'car_plate_number' => $data['car_plate_number'],
            'source' => $data['source'],
            'status' => self::STATUS_WAIT,
            'originator' => $data['originator'],
            'createtime' => $time
        ];
        $res_changeOrder = self::create($add_ChangeOrder_data);

        $res_lock = self::lockAll($res_changeOrder);

        //修改拍单上争议状态
        $o = new AuOrder($data['order_id']);
        $res_order_dispute = $o->update(['is_dealer_issue' => 1]);
        if ($res_changeOrder && $res_lock && $res_order_dispute) {
            //事务提交
            M()->commit();
            //变更表操作日志表
            $changeOrder_log = [
                'mid' => $res_changeOrder,
                'emp_id' => $data['originator'],
                'desc' => 1,
                'createtime' => $time
            ];
            $res_changeOrder_log = M('modifylist_operation_log')->add($changeOrder_log);
            return true;
        } else {
            M()->rollback();
            return false;
        }
    }


    /**
     *变更单修改
     */
    public function updateChangeOrder($data = array())
    {
        $map = [];
        $map['mid'] = $this->mid;
        $update = M('modify_list')->where($map)->save($data);
        return $update;
    }

    //
    public static function detailMap($map)
    {
        return M('modify_list')->where($map)->find();
    }


    //单条变更单信息
    public function detail()
    {
        $map = [];
        $map['mid'] = $this->mid;
        return M('modify_list')->where($map)->find();
    }

    public static function getOneInfo($mid)
    {
        $map = [];
        $map['mid'] = $mid;
        return M('modify_list')->where($map)->find();
    }

    /**
     * 变更单详情
     * @return  array
     */
    public function ChangeOrderDetail()
    {

        $cols = "m.*,po.amount as success_price,c.brand_id,c.series_id,c.car_no,c.sno,c.car_source,c.model_id,cd.contact_person,du.uid,co.seller_name,co.phone,of.final_price,po.purchase_order_nu";
        $prefix = C('DB_PREFIX');
        $map = array();
        $map['m.mid'] = array('eq', $this->mid);
        $res = M('modify_list')->alias('m')->field($cols)
            ->join($prefix . "order as o ON o.order_id = m.order_id")
            ->join($prefix . "purchase_order as po ON po.id = m.po_id")
            ->join($prefix . "cars as c ON o.car_id = c.car_id")
            ->join('LEFT JOIN ' . $prefix . "order_fee as of ON of.order_id = o.order_id")
            ->join('LEFT JOIN ' . $prefix . "car_owner as co ON co.owner_id = c.owner_id")
            ->join('LEFT JOIN ' . $prefix . "car_dealer as cd ON cd.dealer_id = o.success_dealer_id")
            ->join('LEFT JOIN ' . $prefix . "dealer_user as du ON cd.dealer_id = du.dealer_id")
            ->where($map)->find();
        if(!empty($res)){
            $dealer = new Dealer();
            $res= $dealer->get_contact_mobile_byAntNestfind($res);
        }
        $cm = new CarModel();
        $brand = $cm->get_model_by_id($res['brand_id'], 'brand');
        $series = $cm->get_model_by_id($res['series_id'], 'series');
        $model = $cm->get_model_by_id($res['model_id']);
        $res['model'] = $brand['name'] . ' ' . $series['name'] . ' ' . $model['name'];
        //买家付款账号信息
        $buyerPaymentInfo = self::sellerBuyerPaymentInfo($res['mid'], 1);
        // $res['pay_type'] = $paymentInfo['pay_type'];
        $res['buyer_card_no'] = $buyerPaymentInfo['card_no'];
        $res['buyer_bank_name'] = $buyerPaymentInfo['bank_name'];
        $res['buyer_account_name'] = $buyerPaymentInfo['account_name'];

        //卖家付款账号信息
        $sellerPaymentInfo = self::sellerBuyerPaymentInfo($res['mid'], 0);
        // $res['pay_type'] = $paymentInfo['pay_type'];
        $res['seller_card_no'] = $sellerPaymentInfo['card_no'];
        $res['seller_bank_name'] = $sellerPaymentInfo['bank_name'];
        $res['seller_account_name'] = $sellerPaymentInfo['account_name'];

        //付款信息
        $po = new PurchaseOrder($res['po_id']);
        $payment_id = $po->getPaymentIdByPoid($res['car_source']);
        $res['real_payment'] = 0;
        if ($payment_id) {
            $p = new Payment($payment_id);
            $paymentInfo = $p->getInfo();
            if ($paymentInfo['status'] == 1) {
                $res['real_payment'] = $paymentInfo['amount'];  //实付
            }
        }

        //收款信息
        $o = new AuOrder($res['order_id']);
        $collection_id = $o->getCollectionIdByOid();
        $res['real_collection'] = 0;
        if ($collection_id) {
            $c = new Collection($collection_id);
            $collectionInfo = $c->getInfo();
            if ($collectionInfo['status'] == 1) {
                $res['real_collection'] = $collectionInfo['amount']; //实收
            }
        }
        $modifylist_log = $this->get_modifylist_log();
        $res['modifylist_log'] = $modifylist_log;
        // dump($res);
        return $res;
    }

    /**
     * 变更单列表
     * @return   array
     */
    public static function ChangeOrderList($page = 1, $size = 10, $params)
    {
        $page = (int)$page < 1 ? 1 : (int)$page;
        $size = (int)$size < 1 ? 10 : (int)$size;
        $map = array();
        if ($params['status'] == 0) {
            $map[] = array('m.status' => 0);
            $order = "m.createtime desc";
        } elseif ($params['status'] == 1) {
            $map[] = array('m.status' => 1);
            $order = "m.dealtime desc";
        } elseif ($params['status'] == 2) {
            $map[] = array('m.status' => 2);
            $order = "m.completetime desc";
        } elseif ($params['status'] == 3) {
            $map[] = array('m.status' => 3);
            $order = "m.refusetime desc";
        } elseif ($params['status'] == 4) {
            $map[] = array('m.status' => 4);
            $order = "m.canceltime desc";
        }
        if ($params['order_no']) {
            $map['m.order_no'] = array('like', $params['order_no'] . '%');
        }
        if ($params['sno']) {
            $map['c.sno'] = array('like', $params['sno'] . '%');
        }
        if ($params['modify_no']) {
            $map['m.modify_no'] = array('like', $params['modify_no'] . '%');
        }
        if ($params['car_plate_number']) {
            $map['m.car_plate_number'] = array('like', $params['car_plate_number'] . '%');
        }
        if (!empty($params['location_area'])) {
            $map['c.location_area'] = array('in', $params['location_area']);
        }
        $cols = "m.*,c.car_no,c.sno,c.brand_id,c.series_id,c.model_id,o.order_no,e.real_name";
        $prefix = C('DB_PREFIX');
        $total = M('modify_list')->alias('m')
            ->join($prefix . "order as o ON o.order_id = m.order_id")
            ->join($prefix . "cars as c ON o.car_id = c.car_id")
            ->join('LEFT JOIN ' . $prefix . "employee as e ON e.emp_id = m.originator")
            ->where($map)->count();

        $list = M('modify_list')->alias('m')->field($cols)
            ->join($prefix . "order as o ON o.order_id = m.order_id")
            ->join($prefix . "cars as c ON o.car_id = c.car_id")
            ->join('LEFT JOIN ' . $prefix . "employee as e ON e.emp_id = m.originator")
            ->where($map)->limit($size)->page($page)->order($order)->select();
        $cm = new CarModel();
        // echo M()->getlastsql();
        //数据处理
        if (!empty($list)) {
            foreach ($list as $key => $val) {
                $list[$key] = $val;
                $brand = $cm->get_model_by_id($val['brand_id'], 'brand');
                $series = $cm->get_model_by_id($val['series_id'], 'series');
                $model = $cm->get_model_by_id($val['model_id']);
                $list[$key]['model'] = $brand['name'] . ' ' . $series['name'] . ' ' . $model['name'];
                //是否能作废
                //1)如果是由变更单产生收付款信息已付一笔，变更单不能作废
                $is_show_invalid = false;
                if ($val['status'] == 0) {
                    $is_show_invalid = true;
                }
                $list[$key]['is_show_invalid'] = $is_show_invalid;
                // $manyPaymentInfo = self::paymentInfoByMid($val['mid']);
                // foreach ($manyPaymentInfo as $k => $v) {
                //     if ($v['status'] == 1) {
                //         $is_show_invalid = false;
                //     }
                // }
                // $manyPaymentInfo = self::collectionInfoByMid($val['mid']);
                // foreach ($manyPaymentInfo as $k => $v) {
                //     if ($v['status'] == 1) {
                //         $is_show_invalid = false;
                //     }
                // }
                // //2)车主违约不能作废
                // if ($val['source'] == 9 || $val['source'] == 8) {
                //     $is_show_invalid = false;
                // }
                // //3)如果违约车辆中已处理，不能作废
                // $BreachCarInfo = BreachCar::BreachCarByMid($val['mid']);
                // if ($BreachCarInfo && $BreachCarInfo['status'] > 0) {
                //     $is_show_invalid = false;
                // }
                // //4)如果是贷款，变更单不能作废
                // $o = new AuOrder($val['order_id']);
                // $orderInfo = $o->detail();
                // if ($orderInfo['dealer_pay_mode'] == 2) {
                //     $is_show_invalid = false;
                // }
                // //5)如果是争议来的变更单，变更单不能作废
                // if ($val['did'] > 0) {
                //     $is_show_invalid = false;
                // }

                // //是否可以再次变更  只有争议赔付才能再次变更
                // $is_again_change = false;
                // if (($val['source'] == 7 || $val['source'] == 8) && $val['modify_result'] == 1) {
                //     $is_again_change = true;
                // }
                // $list[$key]['is_again_change'] = $is_again_change;
            }
        }
        $result = array(
            'list' => $list,
            'total' => $total
        );
        return $result;
    }

    /**
     * 车商处理
     * @return  bool
     */
    public function dealerDeal($data)
    {
        //事务开始
        M()->startTrans();
        $coDetail = $this->detail();
        $now = date('Y-m-d H:i:s');
        //变更单状态修改已执行
        $update_ChangeOrder_data = [
            'status' => self::STATUS_ALREADY,
            'modify_reason' => $data['modify_reason'],
            'modify_result' => $data['modify_result'],
            'modify_desc' => $data['modify_desc'],
            'dealer_deduction' => $data['dealer_deduction'],
            'dealtime' => $now
        ];
        $res_changeOrder = $this->updateChangeOrder($update_ChangeOrder_data);
        if(!$res_changeOrder){
            Log::record("order_id:{$coDetail['order_id']},更新变更单失败","ERR",true);
            M()->rollback();
            return false;
        }
        /****车商违约*****/
        //判断车商是否付款
        //是：从付车款中扣除违约金  1)付车款>违约金 生成一条车商应退付款记录  2)付车款<违约金 生成一条车商违约金扣除收款记录
        //否：从保证金里面扣除违约金，并且解冻剩余保证金额，生成一条保证金违约扣除的收款记录

        //找到上一变更单车商赔款，作废上一变更单以及付款
        $res_void_last_change = true;
        $lastData = [];
        $lastData['sid'] = $coDetail['sid'];
        $lastData['mid'] = $coDetail['mid'];
        $lastData['is_dealer'] = 1;//车商
        $last_change_info = self::getLastChangeOrder($lastData);
        if ($last_change_info) {
            $res_void_last_change = self::voidLastChange($last_change_info['mid']);
            if(!$res_void_last_change){
                Log::record("order_id:{$coDetail['order_id']} 作废上一变更单失败","ERR",true);
                M()->rollback();
                return false;
            }
        }

        $o = new AuOrder($coDetail['order_id']);
        $orderInfo = $o->detail();
        $CarReport = new CarReportLogic($orderInfo['car_id']);
        $branch_id = $CarReport ->getBranchId();
        $payment_data = [
            'pay_way' => 1, //1转账
            'create_time' => $now,
            'status' => 0,
            'branch_id'=>$branch_id,
            'card_no' => $data['bank_account'],
            'bank_name' => $data['bank_name'],
            'account_name' => $data['account_name']
        ];
        $collection_data = [
            'payment_method' => 1, //1转账
            'branch_id'=>$branch_id,
            'create_time' => $now,
            'status' => 0
        ];
        $res_pc = true;
        $res_payment_relevant = true;
        $o = new AuOrder($coDetail['order_id']);
        $orderInfo = $o->detail();
        $collection_id = $o->getCollectionIdByOid();
        if (!$collection_id) {
            //未结算 未生成收款记录
            $assertCenter = new AssetCenter($orderInfo['success_dealer_id']);
            $assertParams = array(
                'order_id' => $coDetail['order_id'],
                'dealer_id' => $orderInfo['success_dealer_id'],
                'order_no' => $orderInfo['order_no'],
                'occur_money' => $data['violate_amount'],
                'use_detail' => "保证金中扣除",
            );
            //保证金中扣除车商违约金
            $resViolateBail = $assertCenter->occurViolate($assertParams);
            if(!$resViolateBail){
                Log::record("order_id:{$coDetail['order_id']} 扣除车商违约金失败","ERR",true);
                M()->rollback();
                return false;
            }
            if ($data['violate_amount'] > 0) {
                $collection_data['payment_type'] = 6;
                $collection_data['status'] = 1;
                $collection_data['amount'] = $data['violate_amount'];
                $collection_data['emp_name'] = '系统';
                $collection_data['emp_id'] = C('SYSTEM_EMP_ID.0');
                $collection_data['update_time'] = $now;
                $res_pc = Collection::add($collection_data);
                if (!$res_pc){
                    Log::record("order_id:{$coDetail['order_id']} 生成收款信息失败","ERR",true);
                    M()->rollback();
                    return false;
                }
                $ccData = [
                    'change_id' => $coDetail['mid'],
                    'collection_id' => $res_pc,
                    'payment_type' => $collection_data['payment_type']
                ];
                //变更单生成付款信息中间表
                $res_payment_relevant = self::addCollectionRelevant($ccData);
                if (!$res_payment_relevant){
                    Log::record("order_id:{$coDetail['order_id']} 生成收款信息中间表失败","ERR",true);
                    M()->rollback();
                    return false;
                }
            };
            // //扣保证金 变更单已完成
            $res_change_order = ChangeOrder::changeOrderSucc($coDetail['mid']);

        } else {
            $c = new Collection($collection_id);
            $collection_info = $c->getInfo();
            if ($collection_info['status'] == 1) {
                //已付
                if ($collection_info['amount'] > $data['violate_amount']) {
                    $payment_data['pay_type'] = 4;
                    $payment_data['amount'] = $collection_info['amount'] - $data['violate_amount'];
                    if ($payment_data['amount'] > 0) {
                        $res_pc = Payment::add($payment_data);
                        if (!$res_pc){
                            Log::record("order_id:{$coDetail['order_id']} 生成付款信息失败","ERR",true);
                            M()->rollback();
                            return false;
                        }
                        $prData = [
                            'change_id' => $coDetail['mid'],
                            'payment_id' => $res_pc,
                            'pay_type' => $payment_data['pay_type']
                        ];
                        //变更单生成付款信息中间表
                        $res_payment_relevant = self::addPaymentRelevant($prData);
                        if (!$res_payment_relevant){
                            Log::record("order_id:{$coDetail['order_id']} 生成付款信息中间表失败","ERR",true);
                            M()->rollback();
                            return false;
                        }
                    }
                    //解冻保证金
                    $res_bail = AssetCenter::unfreeze($orderInfo['success_dealer_id'],$coDetail['order_id']);
                } elseif ($collection_info['amount'] < $data['violate_amount']) {
                    $collection_data['amount'] = $data['violate_amount'] - $collection_info['amount'];
                    $collection_data['payment_type'] = 6;
                    $collection_data['status'] = 1;
                    $collection_data['emp_name'] = '系统';
                    $collection_data['emp_id'] = C('SYSTEM_EMP_ID.0');
                    $collection_data['update_time'] = $now;
                    $assertCenter = new AssetCenter($orderInfo['success_dealer_id']);
                    $assertParams = array(
                        'order_id' => $coDetail['order_id'],
                        'dealer_id' => $orderInfo['success_dealer_id'],
                        'order_no' => $orderInfo['order_no'],
                        'occur_money' =>$collection_data['amount'],
                        'use_detail' => "保证金中扣除",
                    );
                    $resViolateBail = $assertCenter->occurViolate($assertParams);
                    if(!$resViolateBail){
                        Log::record("order_id:{$coDetail['order_id']} 扣除车商违约金失败","ERR",true);
                        M()->rollback();
                        return false;
                    }

                    //生成一条收款记录（已收）
                    if ($collection_data['amount'] > 0) {
                        $res_pc = Collection::add($collection_data);
                        if (!$res_pc){
                            Log::record("order_id:{$coDetail['order_id']} 生成收款信息（已收）失败","ERR",true);
                            M()->rollback();
                            return false;
                        }
                        $ccData = [
                            'change_id' => $coDetail['mid'],
                            'collection_id' => $res_pc,
                            'payment_type' => $collection_data['payment_type']
                        ];
                        //变更单生成收款信息中间表
                        $res_payment_relevant = ChangeOrder::addCollectionRelevant($ccData);
                        if (!$res_payment_relevant){
                            Log::record("order_id:{$coDetail['order_id']} 生成付款信息中间表失败","ERR",true);
                            M()->rollback();
                            return false;
                        }
                    }
                    //扣保证金 变更单已完成
                    $res_co_succ = ChangeOrder::changeOrderSucc($coDetail['mid']);
                }elseif ($collection_info['amount'] == $data['violate_amount']){
                    $res_co_succ = ChangeOrder::changeOrderSucc($coDetail['mid']);
                }
            } elseif ($collection_info['status'] == 2) {
                //未付
                $update_ChangeOrder_data['status'] = self::STATUS_COMPLETE;
                $update_ChangeOrder_data['completetime'] = $now;
                $assertCenter = new AssetCenter($orderInfo['success_dealer_id']);
                $assertParams = array(
                    'order_id' => $coDetail['order_id'],
                    'dealer_id' => $orderInfo['success_dealer_id'],
                    'order_no' => $orderInfo['order_no'],
                    'occur_money' => $data['violate_amount'],
                    'use_detail' => "保证金中扣除",
                );
                $resViolateBail = $assertCenter->occurViolate($assertParams);
                if (!$resViolateBail){
                    Log::record("order_id:{$coDetail['order_id']} 扣除车商违约金失败","ERR",true);
                    M()->rollback();
                    return false;
                }
                if ($data['violate_amount'] > 0) {
                    $collection_data['payment_type'] = 6;
                    $collection_data['status'] = 1;
                    $collection_data['amount'] = $data['violate_amount'];
                    $collection_data['emp_name'] = '系统';
                    $collection_data['emp_id'] = C('SYSTEM_EMP_ID.0');
                    $collection_data['update_time'] = $now;
                    $res_pc = Collection::add($collection_data);
                    $ccData = [
                        'change_id' => $coDetail['mid'],
                        'collection_id' => $res_pc,
                        'payment_type' => $collection_data['payment_type']
                    ];
                    //变更单生成付款信息中间表
                    $res_payment_relevant = self::addCollectionRelevant($ccData);
                }
                //扣保证金 变更单已完成
                $res_co_succ = ChangeOrder::changeOrderSucc($coDetail['mid']);
            }
        }

        //是否是自收车辆 是自收流到自收车辆 否流入违约车辆
        $car = new Car($orderInfo['car_id']);
        $carInfo = $car ->detail();
        $breach_car_info = array(
            'sid' => $orderInfo['sid'],
            'car_id' => $orderInfo['car_id'],
            'mid' => $this->mid,
            'order_id'=>$coDetail['order_id']
        );

        if ($carInfo['is_self_receive'] == 1) {
            $breach_car_info['createtime'] = $now;
            $resCar = SelfReceiveCar::create($breach_car_info);
            if (!$resCar) {
                Log::record("order_id:{$coDetail['order_id']} 添加自收车辆处理失败","ERR",true);
                M()->rollback();
                return false;
            }
        }else{
            $breach_car_info['create_time'] = $now;
            $resCar = BreachCar::create($breach_car_info);
            if (!$resCar) {
                Log::record("order_id:{$coDetail['order_id']} 添加违约车辆处理失败","ERR",true);
                M()->rollback();
                return false;
            }
        }

        //如果是过户产生的违约，需要将其放到过户失败里面
        if (in_array($orderInfo['status'],[9,10])) {
            $trans = new Transfer($coDetail['order_id']);
            $transData = [];
            $transData['result'] = 3;
            $transData['last_update'] = $now;
            $transfer = $trans ->update($transData);
        }

        //拍单解锁失败
        $res_order = $o->unLockFailByOrderId();
        if (!$res_order){
            Log::record("order_id:{$coDetail['order_id']} 拍单解锁失败","ERR",true);
            M()->rollback();
            return false;
        }

        //收款解锁关闭
        if ($collection_id && $collection_info['status'] == 2) {
            $res_collection = Collection::invalid($collection_id);
            if (!$res_collection) {
                Log::record("order_id:{$coDetail['order_id']} 收款解锁关闭失败","ERR",true);
                M()->rollback();
                return false;
            }
        }
        //拍单上争议状态
        $res_o = $o->update(['dealer_issue_status' => 3]);
        if (!$res_o){
            Log::record("order_id:{$coDetail['order_id']} 拍单争议状态修改失败","ERR",true);
            M()->rollback();
            return false;
        }
        //事务提交
        M()->commit();
        //变更表操作日志表
        $changeOrder_log = [
            'mid' => $this->mid,
            'emp_id' => $data['emp_id'],
            'desc' => 2,
            'createtime' => $now
        ];
        M('modifylist_operation_log')->add($changeOrder_log);
        //记录操作日志
        $this->record_log($coDetail['order_id'], $orderInfo['car_id'], $data['emp_id'], "变更单买方违约");
        return true;
    }

    /**
     * 车主违约
     * @return  bool
     */
    public function ownerDeal($data)
    {
        //事务开始
        M()->startTrans();
        $coDetail = $this->detail();
        $now = date('Y-m-d H:i:s');
        //变更单状态修改已执行
        $update_ChangeOrder_data = [
            'status' => self::STATUS_ALREADY,
            'modify_reason' => $data['modify_reason'],
            'modify_result' => $data['modify_result'],
            'modify_desc' => $data['modify_desc'],
            'dealer_compensate' => $data['dealer_compensate'],
            'owner_deduction' => $data['owner_deduction'],
            'dealtime' => $now
        ];
        /**
         * 车主违约
         *车商赔偿 车主扣除
         *判断跟车主付过款（扣除）
         *是：生成一条应收车主收款记录
         *否：生成一条车主违约金扣除收款记录
         *判断是否收过车商付（赔偿）
         *是：生成一条车商应退付款记录
         *否：生成一条车商赔付付款记录
         */
        //找到上一车商车主变更单赔款，作废上一车商车主变更单以及付款
        $res_void_last_change = true;
        $lastData = [];
        $lastData['sid'] = $coDetail['sid'];
        $lastData['mid'] = $coDetail['mid'];
        // $lastData['is_dealer'] = 3;//车商车主
        $last_change_info = self::getOwnerVoidChangeOrder($lastData);
        if ($last_change_info) {
            foreach ($last_change_info as $key => $value) {
                $res_void_last_change = self::voidLastChange($value['mid']);
            }
        }
        $res_payment = true;
        $res_payment_relevant = true;
        $o = new AuOrder($coDetail['order_id']);
        $orderInfo = $o->detail();
        $CarReport = new CarReportLogic($orderInfo['car_id']);
        $branch_id = $CarReport ->getBranchId();
        $payment_data = [
            'pay_way' => 1, //1转账
            'create_time' => $now,
            'status' => 0,
            'branch_id'=>$branch_id,
            'card_no' => $data['bank_account'],
            'bank_name' => $data['bank_name'],
            'account_name' => $data['account_name']
        ];
        //收款
        $o = new AuOrder($coDetail['order_id']);
        $orderInfo = $o->detail();
        $collection_id = $o->getCollectionIdByOid();
        if (!$collection_id) {
            //未结算 未生成收款记录
            $payment_data['pay_type'] = 5;
            $payment_data['amount'] = $data['payment_amount'];
        } else {
            $c = new Collection($collection_id);
            $collection_info = $c->getInfo();
            if ($collection_info['status'] == 2) {
                //未收
                $payment_data['pay_type'] = 5;
                $payment_data['amount'] = $data['payment_amount'];
            } elseif ($collection_info['status'] == 1) {
                //已收
                $payment_data['pay_type'] = 4;
                $payment_data['amount'] = $data['payment_amount'] + $collection_info['amount'];
            }
        }
        if ($payment_data['amount'] > 0) {
            $res_payment = Payment::add($payment_data);
            $prData = [
                'change_id' => $coDetail['mid'],
                'payment_id' => $res_payment,
                'pay_type' => $payment_data['pay_type']
            ];
            //变更单生成付款信息中间表
            $res_payment_relevant = self::addPaymentRelevant($prData);
        }


        $collection_data = [
            'payment_method' => 1, //1转账
            'branch_id'=>$branch_id,
            'create_time' => $now,
            'status' => 0
        ];
        $res_owner_payment = true;
        $res_owner_paymentrelevant = true;
        $po = new PurchaseOrder($coDetail['po_id']);
        $Car = new Car($orderInfo['car_id']);
        $carInfo = $Car->detail();
        $payment_id = $po->getPaymentIdByPoid($carInfo['car_source']);
        if (!$payment_id) {
            $collection_data['payment_type'] = 8;
            $collection_data['amount'] = $data['collection_amount'];
            if ($collection_data['amount'] > 0) {
                $res_owner_payment = Collection::add($collection_data);
                $ccData = [
                    'change_id' => $coDetail['mid'],
                    'collection_id' => $res_owner_payment,
                    'payment_type' => $collection_data['payment_type']
                ];
                //变更单生成付款信息中间表
                $res_owner_paymentrelevant = self::addCollectionRelevant($ccData);
            }

        } else {
            $payment = new Payment($payment_id);
            $payment_info = $payment->getInfo();
            if ($payment_info['status'] == 2) {
                //未付
                $collection_data['payment_type'] = 8;
                $collection_data['amount'] = $data['collection_amount'];
                if ($collection_data['amount'] >0) {
                    $res_owner_payment = Collection::add($collection_data);
                    $ccData = [
                        'change_id' => $coDetail['mid'],
                        'collection_id' => $res_owner_payment,
                        'payment_type' => $collection_data['payment_type']
                    ];
                    //变更单生成付款信息中间表
                    $res_owner_paymentrelevant = self::addCollectionRelevant($ccData);
                }
            } elseif ($payment_info['status'] == 1) {
                //已付
                //车主应收
                $collection_data['payment_type'] = 7;
                $collection_data['amount'] = $payment_info['amount'];
                if ($collection_data['amount'] > 0) {
                    $res_owner_payment = Collection::add($collection_data);
                    $ccData = [
                        'change_id' => $coDetail['mid'],
                        'collection_id' => $res_owner_payment,
                        'payment_type' => $collection_data['payment_type']
                    ];
                    //变更单生成付款信息中间表
                    $res_owner_paymentrelevant = self::addCollectionRelevant($ccData);
                }

                if ($res_owner_payment && $res_owner_paymentrelevant) {
                    //车主违约金扣除
                    $collection_data['payment_type'] = 8;
                    $collection_data['amount'] = $data['collection_amount'];
                    if ($collection_data['amount'] > 0) {
                        $res_owner_payment = Collection::add($collection_data);
                        $ccData = [
                            'change_id' => $coDetail['mid'],
                            'collection_id' => $res_owner_payment,
                            'payment_type' => $collection_data['payment_type']
                        ];
                        //变更单生成付款信息中间表
                        $res_owner_paymentrelevant = self::addCollectionRelevant($ccData);
                    }
                } else {
                    return false;
                }
            }
        }
        $res_changeOrder = $this->updateChangeOrder($update_ChangeOrder_data);
        //解冻保证金
        $res_bail = AssetCenter::unfreeze($orderInfo['success_dealer_id'], $coDetail['order_id']);

        //如果是过户产生的违约，需要将其放到过户失败里面
        if (in_array($orderInfo['status'],[9,10])) {
            $trans = new Transfer($coDetail['order_id']);
            $transData = [];
            $transData['result'] = 3;
            $transData['last_update'] = $now;
            $transfer = $trans ->update($transData);
        }
        //拍单解锁失败
        $res_order = $o->unLockFailByOrderId();
        ///采购单作废
        $res_purchase_order = $po->closeById();
        //付款单作废(采购单)
        $invalid_payment = true;
        if ($payment_id && $payment_info['status'] == 2) {
            $invalid_payment = Payment::invalid($payment_id);
        }
        //收款单作废(拍单)
        $res_collection = true;
        if ($collection_id && $collection_info['status'] == 2) {
            $res_collection = Collection::invalid($collection_id);
        }
        //拍单上争议状态
        $res_o = $o->update(['dealer_issue_status' => 5]);
        // dump($res_changeOrder);
        // dump($res_payment);
        // dump($res_payment_relevant);
        // dump($res_owner_payment);
        // dump($res_owner_paymentrelevant);
        // dump($res_order);
        // dump($res_purchase_order);
        // dump($invalid_payment);
        // dump($res_collection);
        // die();
        //更改车源状态
        $CarSource = new CarSource($carInfo['sid']);
        $csData = [];
        $csData['status'] = 600;
        $res_cs = $CarSource->update($csData);
        //更改cars状态
        $res_cars = $Car->update(['car_status' => 8]);
        if ($res_void_last_change && $res_changeOrder && $res_payment && $res_payment_relevant && $res_owner_payment && $res_owner_paymentrelevant && $res_order && $res_purchase_order && $invalid_payment && $res_collection) {
            //事务提交
            M()->commit();
            //变更表操作日志表
            $changeOrder_log = [
                'mid' => $this->mid,
                'emp_id' => $data['emp_id'],
                'desc' => 2,
                'createtime' => $now
            ];
            $res_changeOrder_log = M('modifylist_operation_log')->add($changeOrder_log);
            //记录操作日志
            $log = $this->record_log($coDetail['order_id'], $orderInfo['car_id'], $data['emp_id'], "变更单卖方违约");
            return true;
        } else {
            M()->rollback();
            return false;
        }
    }

    //作废上一变更单以及产生的付款信息
    public static function voidLastChange($mid)
    {
        //作废变更单
        $time = date('Y-m-d H:i:s');
        $res_void_change_order = M('modify_list')->where(['mid' => $mid])->save(['status' => 4, 'canceltime' => $time]);
        //作废生成付款记录
        $paymentIds = self::paymentInfoByMid($mid);
        $res_void_payment = true;
        if ($paymentIds) {
            $paymentId = $paymentIds[0]['payment_id'];
            $res_void_payment = Payment::invalid($paymentId);
        }
        //如果是由争议产生的变更单，需要将该争议单置为作废
        $changeInfo = self::getOneInfo($mid);
        $res_dis = true;
        if ($changeInfo['did']>0) {
            $dis = new Dispute($changeInfo['did']);
            $res_dis = $dis->update(['status'=>4,'canceltime'=>$time]);
        }
        if ($res_void_change_order && $res_void_payment && $res_dis) {
            //变更表操作日志表
            $changeOrder_log = [
                'mid' => $mid,
                'emp_id' => C('SYSTEM_EMP_ID.0'),
                'desc' => 4,
                'createtime' => $time
            ];
            $res_changeOrder_log = M('modifylist_operation_log')->add($changeOrder_log);
            return true;
        } else {
            return false;
        }
    }

    /**
     *获取日志信息
     */
    public function get_modifylist_log()
    {
        $prefix = C('DB_PREFIX');
        $res = M('modifylist_operation_log')->alias('m')->field('m.*,e.real_name')
            ->join('LEFT JOIN ' . $prefix . "employee as e ON e.emp_id = m.emp_id")
            ->where(['mid' => $this->mid])->order('m.createtime asc,m.`desc` asc')->select();
        return $res;
    }


    /**
     * 变更单作废
     */
    public function modifylist_cancel($data)
    {
        //事务开始
        M()->startTrans();
        $update_ChangeOrder_data = [
            'status' => 4,
            'is_auto_void' => 2,
            'canceltime' => date('Y-m-d H:i:s')
        ];
        $res_changeOrder = $this->updateChangeOrder($update_ChangeOrder_data);
        $changeInfo = $this->detail();
        //拍单解锁
        $o = new AuOrder($changeInfo['order_id']);
        $orderInfo = $o->detail();
        $res_order = true;
        // if ($orderInfo['status'] == 12) {
        //     $res_order = $o->update(['status' => $changeInfo['order_status']]);
        //}
        if ($orderInfo['is_lock'] == 1) {
            $res_order = $o->unLockByOrderId();
        }
        ///采购单解锁
        $po = new PurchaseOrder($changeInfo['po_id']);
        $purchaseInfo = $po->viewById();
        $res_purchase_order = true;
        if ($purchaseInfo['is_lock'] == 1) {
            $res_purchase_order = $po->edit(['is_lock' => 0]);
        }
        //付款单解锁(采购单)
        $Car = new Car($orderInfo['car_id']);
        $carInfo = $Car->detail();
        $payment_id = $po->getPaymentIdByPoid($carInfo['car_source']);
        $res_payment = true;
        if ($payment_id) {
            $res_payment = Payment::unLock($payment_id);
        }
        //收款解锁(拍单)
        $collection_id = $o->getCollectionIdByOid();
        $res_collection = true;
        if ($collection_id) {
            $res_collection = Collection::unLock($collection_id);
        }

        //变更单产生的收付款单要关闭
        // $changeData = [
        //     'mid' => $changeInfo['mid'],
        // ];
        // $res_pc = $this->get_collection_payment($changeData);

        //拍单争议状态修改
        $res_order_dispute_status = $o->update(['dealer_issue_status' => 0, 'is_dealer_issue' => 0]);

        //如果产生违约车辆且违约车辆未处理则关闭
        // $res_bc_car = true;
        // $is_having_breachcar = BreachCar::BreachCarByMid($changeInfo['mid']);
        // if ($is_having_breachcar && $is_having_breachcar['status'] == 0) {
        //     $res_bc_car = BreachCar::updateBreachCar(['status'=>4],$is_having_breachcar['bc_id']);
        // }
        //如果是由争议产生的变更单，需要将该争议单置为驳回
        // $res_dis = true;
        // if ($changeInfo['did']>0) {
        //     $dis = new Dispute($changeInfo['did']); 
        //     $res_dis = $dis->update(['status'=>3,'canceltime'=>date('Y-m-d H:i:s')]);
        // }
        if ($res_changeOrder && $res_order && $res_purchase_order && $res_payment && $res_collection && $res_order_dispute_status) {
            //事务提交
            M()->commit();
            //变更表操作日志表
            $changeOrder_log = [
                'mid' => $this->mid,
                'emp_id' => $data['emp_id'],
                'desc' => 5,
                'createtime' => date('Y-m-d H:i:s')
            ];
            $res_changeOrder_log = M('modifylist_operation_log')->add($changeOrder_log);
            //记录操作日志
            $log = $this->record_log($changeInfo['order_id'], $orderInfo['car_id'], $data['emp_id'], "变更单作废");
            // $log = array('order_id' => $changeInfo['order_id'], 'action' => '变更单作废');
            // \AuctionCore\System\SystemLog::add($log);
            return true;
        } else {
            M()->rollback();
            return false;
        }
    }

    /**
     * 找到变更单ID生成收付款，关闭
     */
    private function get_collection_payment($data)
    {
        $collections = self::collectionInfoByMid($data['mid']);
        $collectionClose = true;
        foreach ($collections as $key => $value) {
            $collectioninfo = Collection::getInfoById($value['collection_id']);
            if ($collectioninfo['status'] == 1) {
                continue;
            } else {
                $collectionClose = Collection::invalid($value['collection_id']);
                if (!$collectionClose) {
                    return false;
                }
            }
        }
        $paymentClose = true;
        $payments = self::paymentInfoByMid($data['mid']);
        foreach ($payments as $k => $v) {
            $paymentinfo = Payment::getInfoById($v['payment_id']);
            if ($paymentinfo['status'] == 1) {
                continue;
            } else {
                $paymentClose = Payment::invalid($v['payment_id']);
                if (!$paymentClose) {
                    return false;
                }
            }
        }
        if ($collectionClose && $paymentClose) {
            return true;
        }
    }

    /**
     * 二次争议详情页
     **/
    public function again_change_detail()
    {
        $cols = "m.*,c.brand_id,c.series_id,c.car_no,c.car_source,c.model_id,cd.contact_person,cd.contact_mobile,co.seller_name,co.phone,of.success_price,of.final_price";
        $prefix = C('DB_PREFIX');
        $map = array();
        $map['m.mid'] = array('eq', $this->mid);
        $res = M('modify_list')->alias('m')->field($cols)
            ->join($prefix . "order as o ON o.order_id = m.order_id")
            ->join($prefix . "cars as c ON o.car_id = c.car_id")
            ->join('LEFT JOIN ' . $prefix . "order_fee as of ON of.order_id = o.order_id")
            ->join('LEFT JOIN ' . $prefix . "car_owner as co ON co.owner_id = c.owner_id")
            ->join('LEFT JOIN ' . $prefix . "car_dealer as cd ON cd.dealer_id = o.success_dealer_id")
            ->where($map)->find();
        $cm = new CarModel();
        $brand = $cm->get_model_by_id($res['brand_id'], 'brand');
        $series = $cm->get_model_by_id($res['series_id'], 'series');
        $model = $cm->get_model_by_id($res['model_id']);
        $res['model'] = $brand['name'] . ' ' . $series['name'] . ' ' . $model['name'];
        if (($res['source'] == 7 || $res['source'] == 8) && $res['modify_result'] == 1) {
            $payment = self::paymentInfoByMid($res['mid']);
            $payment_id = $payment[0]['payment_id'];
            $p = new Payment($payment_id);
            $paymentInfo = $p->getInfo();
            $res['pay_type'] = $paymentInfo['pay_type'];
            $res['pay_amount'] = $paymentInfo['amount'];
            $res['card_no'] = $paymentInfo['card_no'];
            $res['bank_name'] = $paymentInfo['bank_name'];
            $res['account_name'] = $paymentInfo['account_name'];
        }
        //付款信息
        $po = new PurchaseOrder($res['po_id']);
        $payment_id = $po->getPaymentIdByPoid($res['car_source']);
        $p = new Payment($payment_id);
        $onePaymentInfo = $p->getInfo();
        $res['real_payment'] = 0;
        if ($onePaymentInfo['status'] == 1) {
            $res['real_payment'] = $onePaymentInfo['amount'];  //实付
        }
        //收款信息
        $o = new AuOrder($res['order_id']);
        $collection_id = $o->getCollectionIdByOid();
        $c = new Collection($collection_id);
        $collectionInfo = $c->getInfo();
        $res['real_collection'] = 0;
        if ($collectionInfo['status'] == 1) {
            $res['real_collection'] = $collectionInfo['amount']; //实收
        }

        //变更单产生收款信息（未收）
        $change_payment = self::paymentInfoByMid($res['mid']);
        $payment_id = $change_payment[0]['payment_id'];
        $p = new Payment($payment_id);
        $paymentInfo = $p->getInfo();
        $res['change_payment'] = $paymentInfo['amount'];

        // dump($res);
        return $res;
    }


    /**
     * 变更单拒绝执行
     */
    public function refuse_execute($emp_id)
    {
        $update_ChangeOrder_data = [
            'status' => 3,
            'refusetime' => date('Y-m-d H:i:s')
        ];
        $changeInfo = $this->detail();
        $o = new AuOrder($changeInfo['order_id']);
        $orderInfo = $o->detail();
        $res_changeOrder = $this->updateChangeOrder($update_ChangeOrder_data);
        $log = $this->record_log($changeInfo['order_id'], $orderInfo['car_id'], $emp_id, "变更单拒绝执行");
        $changeOrder_log = [
            'mid' => $changeInfo['mid'],
            'emp_id' => $emp_id,
            'desc' => 4,
            'createtime' => date('Y-m-d H:i:s')
        ];
        $res_changeOrder_log = M('modifylist_operation_log')->add($changeOrder_log);
        return $res_changeOrder;
    }

    /**
     * 添加变更单产生付款记录中间表
     **/
    public static function addPaymentRelevant($data)
    {
        $midcpData = [
            'change_id' => $data['change_id'],
            'payment_id' => $data['payment_id'],
            'pay_type' => $data['pay_type'],
            'createtime' => date('Y-m-d H:i:s')
        ];
        return $res_pc = M('change_payment')->add($midcpData);
    }

    /**
     * 添加变更单产生收款记录中间表
     **/
    public static function addCollectionRelevant($data)
    {
        $midccData = [
            'change_id' => $data['change_id'],
            'collection_id' => $data['collection_id'],
            'payment_type' => $data['payment_type'],
            'createtime' => date('Y-m-d H:i:s')
        ];
        return $res_cc = M('change_collection')->add($midccData);
    }

    /**
     *根据变更单找到对应收款
     */
    public function collectionInfoByMid($mid)
    {
        $res = M('change_collection')->where(['change_id' => $mid])->select();
        return $res;
    }

    /**
     *根据变更单找到对应付款
     */
    public static function paymentInfoByMid($mid)
    {
        $res = M('change_payment')->where(['change_id' => $mid])->select();
        return $res;
    }

    /***锁定变更单相关采购单 拍单 收付款单***/
    public static function lockAll($mid)
    {
        $changeDetail = self::getOneInfo($mid);
        //拍单锁定
        $o = new AuOrder($changeDetail['order_id']);
        $orderInfo = $o->detail();
        $res_order = $o->lockByOrderId();
        ///采购单锁定
        $po = new PurchaseOrder($changeDetail['po_id']);
        $res_purchase_order = $po->lockById();
        //付款单锁定(采购单)
        $Car = new Car($orderInfo['car_id']);
        $carInfo = $Car->detail();
        $payment_id = $po->getPaymentIdByPoid($carInfo['car_source']);
        $res_payment = true;
        if ($payment_id) {
            $res_payment = Payment::lock($payment_id);
        }
        //收款锁定(拍单)
        $collection_id = $o->getCollectionIdByOid();
        $res_collection = true;
        if ($collection_id) {
            $res_collection = Collection::lock($collection_id);
        }
        if ($res_order && $res_purchase_order && $res_payment && $res_collection) {
            return true;
        } else {
            return false;
        }
    }


    /**
     *解锁变更单相关采购单 拍单 首付款单
     ***/
    public static function unLockAll($mid)
    {
        $changeDetail = self::getOneInfo($mid);

        //拍单解锁
        $o = new AuOrder($changeDetail['order_id']);
        $orderInfo = $o->detail();
        $res_order = $o->unLockByOrderId();

        ///采购单解锁
        $po = new PurchaseOrder($changeDetail['po_id']);
        $res_purchase_order = $po->unLockById();

        //付款单解锁(采购单)
        $Car = new Car($orderInfo['car_id']);
        $carInfo = $Car->detail();
        $payment_id = $po->getPaymentIdByPoid($carInfo['car_source']);
        $res_payment = true;
        if ($payment_id) {
            $res_payment = Payment::unLock($payment_id);
        }
        //收款解锁(拍单)
        $collection_id = $o->getCollectionIdByOid();
        $res_collection = Collection::unLock($collection_id);

        if ($res_order && $res_purchase_order && $res_payment && $res_collection) {
            return true;
        } else {
            return false;
        }
    }

    private function record_log($order_id, $car_id, $emp_id, $action)
    {
        //记录员工操作日志
        $log = [
            'emp_id' => $emp_id,
            'order_id' => $order_id,
            'car_id' => $car_id,
            'owner_id' => 0,
            'action' => $action
        ];
        \AuctionCore\System\SystemLog::add($log);

        /**
         * 记录车辆跟踪日志
         */
        $car_action_data = array(
            'action_name' => $action,
            'emp_id' => $emp_id
        );
        \AuctionCore\CarResource\Car::add_car_trace_log($car_id, $car_action_data);

        /**
         * 记录拍品跟踪日志
         */
        $order_action_data = array(
            'action_name' => $action,
            'emp_id' => $emp_id
        );
        \AuctionCore\AuctionOrder\AuOrder::add_order_trace_log($order_id, $order_action_data);
    }


    /**
     *作废上一变更单以及变更单生成付款记录
     *生成新的变更单 并且与采购单 拍单绑定关系
     * @param $data array
     * @return bool
     */
     private static function voidLastChangeOrder($data)
     {
         //作废变更单
         $res_void_change_order = M('modify_list')->where(['mid' => $data['mid']])->save(['status' => 4]);
         //作废生成付款记录
         $paymentIds = self::paymentInfoByMid($data['mid']);
         $paymentId = $paymentIds[0]['payment_id'];
         $res_void_payment = Payment::invalid($paymentId);
         //生成新的变更单
         $changeOrderInfo = self::getOneInfo($data['mid']);
         $o = new AuOrder($changeOrderInfo['order_id']);
         $orderInfo = $o->detail();
         $modify_no = genBillsNo('BG', '1');
         $dealer_compensate = $data['dealer_compensate'] ? $data['dealer_compensate'] : 0;
         $owner_compensate = $data['owner_compensate'] ? $data['owner_compensate'] : 0;
         $dealer_deduction = $data['dealer_deduction'] ? $data['dealer_deduction'] : 0;
         $owner_deduction = $data['owner_deduction'] ? $data['owner_deduction'] : 0;
         $add_ChangeOrder_data = [
             'modify_no' => $modify_no,
             'order_id' => $changeOrderInfo['order_id'],
             'order_no' => $changeOrderInfo['order_no'],
             'po_id' => $changeOrderInfo['po_id'],
             'po_no' => $changeOrderInfo['po_no'],
             'car_plate_number' => $changeOrderInfo['car_plate_number'],
             'order_status' => $orderInfo['status'],
             'source' => $changeOrderInfo['source'],
             'modify_reason' => $data['modify_reason'],
             'modify_result' => $data['modify_result'],
             'modify_desc' => $data['modify_desc'],
             'dealer_compensate' => $dealer_compensate,
             'owner_compensate' => $owner_compensate,
             'dealer_deduction' => $dealer_deduction,
             'owner_deduction' => $owner_deduction,
             'status' => 1,
             'originator' => $data['emp_id'],
             'createtime' => date('Y-m-d H:i:s'),
             'dealtime' => date('Y-m-d H:i:s')
         ];
         $res_changeOrder = self::create($add_ChangeOrder_data);

         if ($res_void_change_order && $res_void_payment && $res_changeOrder) {
             return $res_changeOrder;
         } else {
             return false;
         }
     }

    /**
     *车商/车主赔付
     ***/
    public static function dealerOwnerPayment($data)
    {
        //事务开始
        M()->startTrans();
        $newChangeOrderId = self::voidLastChangeOrder($data);
        $changeInfo = self::getOneInfo($newChangeOrderId);
        $newData = [];
        $dealer_payment = [
            'did' => $changeInfo['did'],
            'order_id' => $changeInfo['order_id'],
            'po_id' => $changeInfo['po_id'],
            'change_id' => $newChangeOrderId,
            'bank_account' => $data['bank_account'],
            'bank_name' => $data['bank_name'],
            'account_name' => $data['account_name'],
            'payment_amount' => $data['payment_amount']
        ];
        $res_payment = Dispute::dealer_owner_payment($dealer_payment, $data['od_type']);
        if ($newChangeOrderId > 0 && $res_payment) {
            //事务提交
            M()->commit();
            //变更表操作日志表
            $changeOrder_log = [
                'mid' => $newChangeOrderId,
                'emp_id' => $data['emp_id'],
                'desc' => 2,
                'createtime' => date('Y-m-d H:i:s')
            ];
            $res_changeOrder_log = M('modifylist_operation_log')->add($changeOrder_log);
            //记录操作日志
            $log = array('order_id' => $changeInfo['order_id'], 'action' => '变更单再次变更赔偿');
            \AuctionCore\System\SystemLog::add($log);
            return true;
        } else {
            M()->rollback();
            return false;
        }
    }

    /**
     *车商赔付 ->订单关闭
     ***/
    public static function dealerPaymentColse($data)
    {
        //事务开始
        M()->startTrans();
        $newChangeOrderId = self::voidLastChangeOrder($data);
        $changeInfo = self::getOneInfo($newChangeOrderId);
        $newData = [];
        $dealer_payment = [
            'did' => $changeInfo['did'],
            'order_id' => $changeInfo['order_id'],
            'po_id' => $changeInfo['po_id'],
            'change_id' => $newChangeOrderId,
            'bank_account' => $data['bank_account'],
            'bank_name' => $data['bank_name'],
            'account_name' => $data['account_name'],
            'payment_amount' => $data['payment_amount']
        ];
        $res_payment = Dispute::dealer_order_close($dealer_payment);
        if ($newChangeOrderId > 0 && $res_payment) {
            //事务提交
            M()->commit();
            //变更表操作日志表
            $changeOrder_log = [
                'mid' => $newChangeOrderId,
                'emp_id' => $data['emp_id'],
                'desc' => 2,
                'createtime' => date('Y-m-d H:i:s')
            ];
            $res_changeOrder_log = M('modifylist_operation_log')->add($changeOrder_log);
            //记录操作日志
            $log = array('order_id' => $changeInfo['order_id'], 'action' => '变更单再次订单关闭');
            \AuctionCore\System\SystemLog::add($log);
            return true;
        } else {
            M()->rollback();
            return false;
        }
    }

    /**
     *车主争议 ->订单关闭
     ***/
    public static function ownerPaymentColse($data)
    {
        //事务开始
        M()->startTrans();
        $newChangeOrderId = self::voidLastChangeOrder($data);
        $changeInfo = self::getOneInfo($newChangeOrderId);
        $newData = [];
        $dealer_payment = [
            'did' => $changeInfo['did'],
            'order_id' => $changeInfo['order_id'],
            'po_id' => $changeInfo['po_id'],
            'change_id' => $newChangeOrderId,
            'bank_account' => $data['bank_account'],
            'bank_name' => $data['bank_name'],
            'account_name' => $data['account_name'],
            'payment_amount' => $data['payment_amount'],
            'owner_payment_amount' => $data['owner_payment_money']
        ];
        $res_payment = Dispute::owner_order_close($dealer_payment);
        if ($newChangeOrderId > 0 && $res_payment) {
            //事务提交
            M()->commit();
            //变更表操作日志表
            $changeOrder_log = [
                'mid' => $newChangeOrderId,
                'emp_id' => $data['emp_id'],
                'desc' => 2,
                'createtime' => date('Y-m-d H:i:s')
            ];
            $res_changeOrder_log = M('modifylist_operation_log')->add($changeOrder_log);
            //记录操作日志
            $log = array('order_id' => $changeInfo['order_id'], 'action' => '变更单再次订单关闭');
            \AuctionCore\System\SystemLog::add($log);
            return true;
        } else {
            M()->rollback();
            return false;
        }
    }

    /**
     *再次争议 ->车商违约
     ***/
    public static function dealerViolate($data)
    {
        //事务开始
        M()->startTrans();
        $newChangeOrderId = self::voidLastChangeOrder($data);
        $changeInfo = self::getOneInfo($newChangeOrderId);
        $newData = [];
        $dealer_payment = [
            'did' => $changeInfo['did'],
            'order_id' => $changeInfo['order_id'],
            'po_id' => $changeInfo['po_id'],
            'change_id' => $newChangeOrderId,
            'bank_account' => $data['bank_account'],
            'bank_name' => $data['bank_name'],
            'account_name' => $data['account_name'],
            'payment_amount' => $data['payment_amount']
        ];
        $res_payment = Dispute::dealer_violate($dealer_payment);
        if ($newChangeOrderId > 0 && $res_payment) {
            //事务提交
            M()->commit();
            //变更表操作日志表
            $changeOrder_log = [
                'mid' => $newChangeOrderId,
                'emp_id' => $data['emp_id'],
                'desc' => 2,
                'createtime' => date('Y-m-d H:i:s')
            ];
            $res_changeOrder_log = M('modifylist_operation_log')->add($changeOrder_log);
            //记录操作日志
            $log = array('order_id' => $changeInfo['order_id'], 'action' => '再次变更订单关闭');
            \AuctionCore\System\SystemLog::add($log);
            return true;
        } else {
            M()->rollback();
            return false;
        }
    }

    /**
     *  再次变更 ->车主违约
     **/
    public static function ownerViolate($data)
    {
        //事务开始
        M()->startTrans();
        $newChangeOrderId = self::voidLastChangeOrder($data);
        $changeInfo = self::getOneInfo($newChangeOrderId);
        $newData = [];
        $dealer_payment = [
            'did' => $changeInfo['did'],
            'order_id' => $changeInfo['order_id'],
            'po_id' => $changeInfo['po_id'],
            'change_id' => $newChangeOrderId,
            'bank_account' => $data['bank_account'],
            'bank_name' => $data['bank_name'],
            'account_name' => $data['account_name'],
            'payment_amount' => $data['payment_amount'],
            'owner_payment_amount' => $data['owner_payment_money']
        ];
        $res_payment = Dispute::owner_violate($dealer_payment);
        if ($newChangeOrderId > 0 && $res_payment) {
            //事务提交
            M()->commit();
            //变更表操作日志表
            $changeOrder_log = [
                'mid' => $newChangeOrderId,
                'emp_id' => $data['emp_id'],
                'desc' => 2,
                'createtime' => date('Y-m-d H:i:s')
            ];
            $res_changeOrder_log = M('modifylist_operation_log')->add($changeOrder_log);
            //记录操作日志
            $log = array('order_id' => $changeInfo['order_id'], 'action' => '再次变更订单关闭');
            \AuctionCore\System\SystemLog::add($log);
            return true;
        } else {
            M()->rollback();
            return false;
        }
    }

    //检查变更单产生的收付款是否完成
    public function cashierCallback()
    {
        $collectionStatus = 1;
        $paymentStatus = 1;
        $mid = $this->mid;
        //查询变更单产生的收款是否已收
        $collections = M("change_collection")->where(['change_id' => $mid])->select();
        if (!empty($collections)) {
            $coIds = [];
            foreach ($collections as $co) {
                $coIds[] = $co['collection_id'];
            }
            //查询收款状态
            $status = Collection::checkStatusByIds($coIds);
            Log::record($status, "ERR", true);
            if (!$status) $collectionStatus = 0;
        }
        //查询变更单产生的付款单是否已付
        $payments = M("change_payment")->where(['change_id' => $mid])->select();
        if (!empty($payments)) {
            $payIds = [];
            foreach ($payments as $pay) {
                $payIds[] = $pay['payment_id'];
            }
            //查询收款状态
            $status = Payment::checkStatusByIds($payIds);
            if (!$status) $paymentStatus = 0;;
        }

        $res = true;
        if ($collectionStatus == 1 && $paymentStatus == 1) {
            //变更单变为已完成
            $update_ChangeOrder_data = [
                'status' => 2,
                'completetime' => date('Y-m-d H:i:s')
            ];
            $res = M("modify_list")->where(['mid' => $mid])->save($update_ChangeOrder_data);
            if ($res) {
                $changeOrder_log = [
                    'mid' => $mid,
                    'emp_id'=>C('SYSTEM_EMP_ID.0'),
                    'desc' => 3,
                    'createtime' => date('Y-m-d H:i:s')
                ];
                M('modifylist_operation_log')->add($changeOrder_log);
            }
        }
        return $res;
    }


    /**
     * 根据拍单ID找对应变更单信息
     * @return array
     */
    public static function getChangeByOrderId($order_id)
    {
        $map = [];
        $map['order_id'] = $order_id;
        $map['status'] = ['neq', 4];
        $map['modify_result'] = ['eq',1];
        $changeInfo = M('modify_list')->where($map)->order('mid desc')->select();
        return $changeInfo;
    }

    /**
     * 根据车源ID获取有效的变更单
     * @param $sid
     * @param $source
     * @return mixed
     */
    public static function getChangeInfoBySid($sid,$source = '')
    {
        $map = [];
        $map['sid'] = $sid;
        $map['status'] = ["neq", 4];
	    if($source=='owner'){
		    $map['source'] = 8; //车主争议
	    }
        $map['modify_result'] = 1; //赔付
        return M('modify_list')->where($map)->select();
    }



	/**
     * 将变更单置为成功 添加日志
     * @return bool
     */
    public static function changeOrderSucc($mid)
    {
        if ($mid < 0) return false;
        $time = date('Y-m-d H:i:s');
        $res = M('modify_list')->where(['mid' => $mid])->save(['status' => 2, 'completetime' => $time]);

        $changeOrder_log = [
            'mid' => $mid,
            'emp_id'=>C('SYSTEM_EMP_ID.0'),
            'desc' => 3,
            'createtime' => $time
        ];
        $res_log = M('modifylist_operation_log')->add($changeOrder_log);

        return $res;
    }

    /**
     * 卖家买家付款账号信息
     * @param $mid
     * @param $is_dealer
     * @return bool
     */
    private static function sellerBuyerPaymentInfo($mid, $is_dealer)
    {
        if ($mid < 0) return false;
        $prefix = C('DB_PREFIX');
        $map = array();
        $map['m.mid'] = array('eq', $mid);
        if ($is_dealer == 1) {
            $map['p.pay_type'] = array('in', [4, 5]);
        } else {
            $map['p.pay_type'] = array('eq', 7);
        }
        $res = M('modify_list')->alias('m')->field('p.*')
            ->join($prefix . "change_payment as cp ON cp.change_id = m.mid")
            ->join($prefix . "payment as p ON p.id = cp.payment_id")
            ->where($map)->find();
        return $res;
    }

    //找到上一变更单
    public static function getLastChangeOrder($data)
    {
        $map = [];
        $map['sid'] = $data['sid'];
        $map['mid'] = ['neq', $data['mid']];
        $map['modify_result'] = ['eq',1];
        $map['status'] = ['neq', 4];
        if ($data['is_dealer'] == 1) {
            $map['source'] = ['lt',8];
        }elseif ($data['is_dealer'] == 2){
            $map['source'] = ['gt',7];
        }
        $changeInfo = M('modify_list')->where($map)->order('mid desc')->find();
        return $changeInfo;
    }

    //车主违约 之前产生的所有未作废的变更单
    public static function getOwnerVoidChangeOrder($data){
        $map = [];
        $map['sid'] = $data['sid'];
        $map['mid'] = ['neq', $data['mid']];
        $map['modify_result'] = ['eq',1];
        $map['status'] = ['neq', 4];
        $changeInfo = M('modify_list')->where($map)->select();
        return $changeInfo;
    }

    /**
     * 通过采购单ID获取最新的变更单
     * @param $purchaseId
     * @return mixed
     */
    public static function getLatestChangeOrderByPurchaseOrderId($purchaseId)
    {
        return M("modify_list")->where(['po_id' => $purchaseId])->order("mid desc")->find();
    }

    /**
     * @param $mid
     * @param $action
     * @return array|bool
     */
    public static function getOperatorByMidSAndAction($mid, $action='')
    {
        if ($mid < 1) return false;
        $data = [];
        $where = [
            'mid' => $mid,
        ];
        if(!empty($action)){
            $where['desc'] = $action;
        }
        $emp_id = M('modifylist_operation_log')->where($where)->getField("emp_id");

        if($emp_id>0){
            $employee = M("employee")->field("real_name,mobile")->where(['emp_id'=>$emp_id])->find();
            $data['real_name'] = $employee['real_name'];
            $data['mobile'] = $employee['mobile'];
        }
        return $data;
    }

}
